package com.shanyue.redwine.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.*;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.alibaba.fastjson.JSON;
import com.shanyue.redwine.R;
import com.shanyue.redwine.pay.aili.AlipayAsycnTask;
import com.shanyue.redwine.pay.aili.PayResult;
import com.shanyue.redwine.pay.weixin.WXpayAsyncTask;
import com.shanyue.redwine.pay.weixin.WeChatPayInfo;
import com.shanyue.redwine.utils.Constants;
import com.shanyue.redwine.utils.SweetAlertDialogFactory;
import com.shanyue.redwine.utils.Utils;
import com.shanyue.redwine.utils.X5WebView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient.CustomViewCallback;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.*;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.utils.TbsLog;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.Map;

public class ActivityWeb extends ActivityBase {
    /**
     * 作为一个浏览器的示例展示出来，采用android+web的模式
     */
    private X5WebView mWebView;
    private ViewGroup mViewParent;
    private static final String TAG = "SdkDemo";
    private static final int MAX_LENGTH = 14;
    private boolean mNeedTestPage = false;
    private final int disable = 120;
    private final int enable = 255;
    private ProgressBar mPageLoadingProgressBar = null;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    RxPermissions mRxPermissions = new RxPermissions(this);
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AlipayAsycnTask.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
                        //                        Intent intent = new Intent(mActivity, ActivityOrder.class);
                        //                        intent.putExtra(Constants.KEY_DATA, ActivityOrder
                        // .ORDER_STATE_UN_SEND);
                        //                        startActivity(intent);
                        //                        finish();
                    } else if (TextUtils.equals(resultStatus, "8000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mActivity, "正在处理,请查询订单列表中订单的支付状态", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.equals(resultStatus, "5000")) {
                        Toast.makeText(mActivity, "重复请求,如订单未支付,请稍后再进行支付", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        Toast.makeText(mActivity, "已取消支付", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case AlipayAsycnTask.SDK_PAY_ERROR:
                    Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN);
        try {
            if (Build.VERSION.SDK_INT >= 11) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams
                        .FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
        /*
         * getWindow().addFlags(
         * android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
         */
        setContentView(R.layout.activity_web);
        mViewParent = (ViewGroup) findViewById(R.id.webView1);
        mTestHandler.sendEmptyMessageDelayed(MSG_INIT_UI, 10);
    }


    private void initProgressBar() {
        mPageLoadingProgressBar = (ProgressBar) findViewById(R.id.progressBar1);// new
        // ProgressBar(getApplicationContext(),
        // null,
        // android.R.attr.progressBarStyleHorizontal);
        mPageLoadingProgressBar.setMax(100);
        mPageLoadingProgressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.color_progressbar));
    }

    private void init() {
        mWebView = new X5WebView(this, null);
        mViewParent.addView(mWebView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout
                .LayoutParams.MATCH_PARENT));
        initProgressBar();
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (Constants.ACCEPTED_URI_SCHEME.matcher(url).matches()) {
                    return super.shouldOverrideUrlLoading(view, url);
                } else {
                    return urlAction(url) ? true : super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                //隐藏加载进度条
                //                mPageLoadingProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mPageLoadingProgressBar.setVisibility(View.GONE);
                //                if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 16)
                //                    changGoForwardButton(view);
                /* mWebView.showLog("test Log"); */
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                mPageLoadingProgressBar.setProgress(i);
            }


            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2, JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            View myVideoView;
            View myNormalView;
            CustomViewCallback callback;

            // /////////////////////////////////////////////////////////
            //

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view, CustomViewCallback customViewCallback) {
                FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }

            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2, JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3);
            }


            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }


        });

        mWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            TbsLog.d(TAG, "url: " + url);
            if (mRxPermissions.isGranted(Manifest.permission_group.STORAGE)) {
                SweetAlertDialogFactory.build(mActivity, SweetAlertDialog.WARNING_TYPE).setContentText("是否下载 " +
                        contentDisposition + ",文件大小: " + (contentLength / 1042 / 1024) + "M").setCancelText(getString
                        (R.string.dialog_cancel)).setConfirmText(getString(R.string.ssdk_oks_confirm))
                        .setConfirmClickListener(dialog -> {
                    dialog.dismiss();
                    startDownLoad(url, Constants.DIR_ROOT);
                }).show();
            } else {
                SweetAlertDialogFactory.build(mActivity, SweetAlertDialog.WARNING_TYPE).setContentText
                        ("下载文件需要您授权使用存储权限.").setConfirmText("授权").setConfirmClickListener(dialog -> {
                    mRxPermissions.request(Manifest.permission_group.STORAGE).subscribe(flag -> {
                        if (flag) {
                            SweetAlertDialogFactory.build(mActivity, SweetAlertDialog.WARNING_TYPE).setContentText
                                    ("是否下载 " + contentDisposition + ",文件大小: " + (contentLength / 1042 / 1024) + "M")
                                    .setCancelText(getString(R.string.dialog_cancel)).setConfirmText(getString(R
                                    .string.ssdk_oks_confirm)).setConfirmClickListener(d -> {
                                d.dismiss();
                                startDownLoad(url, Constants.DIR_ROOT);
                            }).show();
                        } else {
                            showToast("已拒绝授权,下载失败");
                        }
                    });
                }).show();
            }


        });
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);

        webSetting.setUserAgentString(webSetting.getUserAgentString() + "androidapp");

        long time = System.currentTimeMillis();
        mWebView.loadUrl(getIntent().getData().toString());
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 启用downloadmanager下载
     *
     * @param url  下载地址
     * @param path 下载文件的根目录,在手机downloads目录下
     */
    private void startDownLoad(String url, String path) {
        DownloadManager dm = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setMimeType("application/vnd.android.package-archive");
        request.setVisibleInDownloadsUi(true);
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, path);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        long enqueue = dm.enqueue(request);
    }

    private boolean urlAction(String url) {
        if (url.startsWith("tel:")) {
            if (mRxPermissions.isGranted(Manifest.permission.CALL_PHONE)) {
                Utils.telTo(mActivity, url.split(":")[1]);
            } else {
                mRxPermissions.request(Manifest.permission.CALL_PHONE).subscribe(flag -> {
                    if (flag) {
                        Utils.telTo(mActivity, url.split(":")[1]);
                    } else {
                        showToast("已拒绝授权,下载失败");
                    }
                });
            }
        } else if (url.startsWith("sms:")) {
            String[] objs = url.split(":");
            Utils.sendSms(mActivity, objs[1], objs.length > 2 ? objs[2] : null);
        } else if (url.startsWith("share:")) {
            Utils.share(mActivity, url.split(":")[1]);
        } else if (url.startsWith(Constants.DEAL_URL_PAY_ALI)) {
            String[] payInfo = url.split(Constants.DEAL_URL_PAY_ALI);
            if (payInfo.length > 1) {
                String payStr = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id" +
                        "=2018051060098236&biz_content=%7B%22body%22%3A%22%E6%88%91%E6%98%AF%E6" +
                        "%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A" +
                        "%221982000000069034414%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY" +
                        "%22%2C%22subject%22%3A%22App%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95Java" + "%22" +
                        "%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A" + "%221" + "%22%7D" +
                        "&charset=UTF-8&format=json&method=alipay.trade" + ".app" + "" + "" + "" + "" + "" +
                        ".pay&notify_url=http%3A%2F%2Fmuvsgp.natappfree" + "" + "" + "" + "" + "" + "" +
                        ".cc%2Fpay%2Falipay%2Fnotify&sign=UDYjFYO9FkqjJNEe45dt3Al8paX%2Bx2NC" +
                        "%2BG3ASaIVrC7ydo1gJiHHn3xllNrPxLSFG9SX2VjI4tdjximxOED5PXf2gdVcC0VvC74Bk4NyawVVFE1aE05smFEoccNCLTj37aZSvbV9MiRYdPKacmqRTVWdogpS2C0lazv1zvO32x5usphNskq7p14TWIpHzb0dAAqZOg2j7%2FjuXgS4ZwW9Itdy%2BIcJakqENNydplR4nR1vEIDhW3sJCJo3qz7bnlkbw0laHW6Hc8GemG17lhStINffERsIhpCRZKtZm9cifJUTi8%2B13BN5541Y4I2ETRNXCOEcqEgPt%2FYkCwPPjA4HvQ%3D%3D&sign_type=RSA2&timestamp=2018-07-25+16%3A53%3A49&version=1.0";
                AlipayAsycnTask task = new AlipayAsycnTask(mActivity, mHandler, payStr);
                //                AlipayAsycnTask task = new AlipayAsycnTask(mActivity, mHandler, payInfo[1]);
                task.execute("");

            } else {
                showToast("参数错误");
            }
        } else if (url.startsWith(Constants.DEAL_URL_PAY_WEIXIN)) {
            String[] payInfo = url.split(Constants.DEAL_URL_PAY_WEIXIN);
            if (payInfo.length > 1) {
                WXpayAsyncTask task = new WXpayAsyncTask(mActivity, JSON.parseObject(payInfo[1], WeChatPayInfo.class));
                task.execute("");
            } else {
                showToast("参数错误");
            }
        } else if (url.startsWith(Constants.DEAL_URL_SCAN)) {
            Intent intent = new Intent(this, ActivityCapture.class);
            // TODO: 2018/8/29 获取token 并存储
            startActivity(intent);
        } else if (url.startsWith(Constants.DEAL_URL_APP_SHARE)) {
            if (url.split(Constants.DEAL_URL_APP_SHARE).length > 1) {
                try {
                    Utils.appShare(mActivity, URLDecoder.decode(url.split(Constants.DEAL_URL_APP_SHARE)[1], "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    showToast("参数错误");
                }
            } else {
                showToast("参数错误");
            }
        } else {
            try {
                Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                intent.setComponent(null);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                    intent.setSelector(null);
                }
                if (getPackageManager().resolveActivity(intent, 0) == null) {//未找到对应的应用程序打开scheme
                    return false;
                } else {
                    startActivity(intent);
                    return true;
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    boolean[] m_selected = new boolean[]{true, true, true, true, false, false, true};

    //    @Override
    //    public boolean onKeyDown(int keyCode, KeyEvent event) {
    //
    //        if (keyCode == KeyEvent.KEYCODE_BACK) {
    //            if (mWebView != null && mWebView.canGoBack()) {
    //                mWebView.goBack();
    ////                if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 16)
    ////                    changGoForwardButton(mWebView);
    //                return true;
    //            } else return super.onKeyDown(keyCode, event);
    //        }
    //        return super.onKeyDown(keyCode, event);
    //    }
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        TbsLog.d(TAG, "onActivityResult, requestCode:" + requestCode + ",resultCode:" + resultCode);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        mWebView.loadUrl(intent.getData().toString());
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            //            mWebView.loadUrl(mHomeUrl);
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    @Override
    protected void onDestroy() {
        if (mTestHandler != null)
            mTestHandler.removeCallbacksAndMessages(null);
        if (mWebView != null)
            mWebView.destroy();
        super.onDestroy();
    }

    public static final int MSG_INIT_UI = 1;
    private final int mUrlStartNum = 0;
    private int mCurrentUrl = mUrlStartNum;
    private Handler mTestHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_INIT_UI:
                    init();
                    break;
            }
            super.handleMessage(msg);
        }
    };

}
